#include "libs/spinlock.h"
#include "kernel/task/task.h"
#include "libs/types.h"
void SpinlockLock(Spinlock* lock)
{
    preempt_disable();
    __asm__ __volatile__("one: \n\t"
                  "lock decq %0\n\t"
                  "jns  three\n\t"
                  "two: \n\t"
                  "pause\n\t"
                  "cmpq $0,%0\n\t"
                  "jle two \n\t"
                  "jmp one \n\t"
                  "three: \n\t"
                  :"=m"(lock->lock)
                  :
                  :"memory");
}

void SpinlockUnlock(Spinlock* lock){
        __asm__ __volatile__("movq $1,%0 \n\t"
                  :"=m"(lock->lock) 
                  :
                  :"memory");
        preempt_enable();
}


int64_t SpinlockTryLock(Spinlock* lock){

	uint64_t tmp_value = 0;
	preempt_disable();
	__asm__	__volatile__	(	"xchgq	%0,	%1	\n\t"
				:"=q"(tmp_value),"=m"(lock->lock)
				:"0"(0)
				:"memory"
			);
	if(!tmp_value)
		preempt_enable();
	return tmp_value;

}